﻿using MySql.Data.MySqlClient;
using NewChillers.Helpers;
using NewChillers.Models;
using NewChillers.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace NewChillers.ViewModels
{
    public class UserInfoViewModel : ObservableObject
    {
        private UserModel _newUser;
        private int _actType; // 操作类型  2:编辑  3:新增
        private readonly Window _window;
        private readonly UserModel _currentUser;

        //private bool _isDetailsEna; // 参数 是否可编辑 用户应该可以编辑账号 这个账号是string 不是自增int
        private bool _isEditButtonVis; // 修改配方 按钮 是否显示
        private bool _isAddButtonVis; // 添加配方 按钮 是否显示
        private bool _isCheck1; // 员工
        private bool _isCheck2; // 管理员

        private UserModel _originalUser; // 保存原始用户数据

        public UserModel NewUser
        {
            get => _newUser;
            set => SetProperty(ref _newUser, value);
        }
        //public bool IsDetailsEna
        //{
        //    get => _isDetailsEna;
        //    set => SetProperty(ref _isDetailsEna, value);
        //}
        public bool IsEditButtonVis
        {
            get => _isEditButtonVis;
            set => SetProperty(ref _isEditButtonVis, value);
        }
        public bool IsAddButtonVis
        {
            get => _isAddButtonVis;
            set => SetProperty(ref _isAddButtonVis, value);
        }
        public bool IsCheck1
        {
            get => _isCheck1;
            set
            {
                if (SetProperty(ref _isCheck1, value) && value)
                {
                    NewUser.UserIdentity = 1;
                    IsCheck2 = false; // 自动取消另一个的选择
                }
            }
        }
        public bool IsCheck2
        {
            get => _isCheck2;
            set
            {
                if (SetProperty(ref _isCheck2, value) && value)
                {
                    NewUser.UserIdentity = 2;
                    IsCheck1 = false; // 自动取消另一个的选择
                }
            }
        }

        public ICommand CloseCommand { get; } // 关闭按钮
        public ICommand UpdateRecipeCommand { get; } // 修改按钮
        public ICommand AddRecipeCommand { get; } // 添加按钮

        public UserInfoViewModel(UserModel newUser, int actType, Window window, UserModel currentUser)
        {
            _originalUser = new UserModel
            {
                UserAccount = newUser.UserAccount,
                UserPassword = newUser.UserPassword,
                UserName = newUser.UserName,
                UserIdentity = newUser.UserIdentity
            };

            _newUser = newUser;
            _actType = actType;
            _window = window;
            _currentUser = currentUser;

            CloseCommand = new RelayCommand(ExecuteClose);
            UpdateRecipeCommand = new RelayCommand(ExecuteUpdate);
            AddRecipeCommand = new RelayCommand(ExecuteAdd);

            InitThisWindowByActType(newUser, actType);
        }

        #region 添加按钮
        private void ExecuteAdd(object obj)
        {
            if (!ValidateInput())
                return;

            try
            {
                if (AddUser())
                {
                    MsgBoxHelper.Success("用户添加成功");
                    _window.DialogResult = true;
                }
                else
                {
                    MsgBoxHelper.Error("用户添加失败");
                }
            }
            catch (MySqlException mysqlEx)
            {
                string friendlyMessage = mysqlEx.Number switch
                {
                    1042 => "无法连接数据库，请检查网络连接",
                    1045 => "数据库访问被拒绝",
                    1146 => "数据库表不存在",
                    1205 => "数据库操作超时，请重试", // 死锁
                    1213 => "事务死锁，请重试",      // 死锁
                    0 => "数据库连接失败，请检查网络",
                    _ => $"数据库操作失败，错误代码: {mysqlEx.Number}"
                };
                // 记录数据库异常的日志
                LogHelper.Error(this.GetType(), "[更新用户] | 数据库异常", mysqlEx, _currentUser.UserAccount);
                MsgBoxHelper.Error(friendlyMessage);
            }
            catch (Exception ex)
            {
                MsgBoxHelper.Error($"添加配方时出错：{ex.Message}");
                LogHelper.Error(this.GetType(), $"[添加用户] | 添加用户失败", ex, _currentUser.UserAccount);
            }
        }

        /// <summary>
        /// 执行添加 返回是否成功
        /// </summary>
        private bool AddUser()
        {
            if (IsUserNameExists(NewUser.UserAccount))
            {
                MsgBoxHelper.Warning("已存在相同的用户账号");
                return false;
            }

            // INSERT INTO user_info (user_account, user_password, user_name, user_identity) VALUES();
            string sql = @"INSERT INTO user_info 
                            (user_account, user_password, user_name, user_identity) 
                            VALUES 
                            (@UserAccount, @UserPassword, @UserName, @UserIdentity)";

            var parameters = new[]
            {
                    new MySqlParameter("@UserAccount", NewUser.UserAccount),
                    new MySqlParameter("@UserPassword", NewUser.UserPassword),
                    new MySqlParameter("@UserName", NewUser.UserName),
                    new MySqlParameter("@UserIdentity", NewUser.UserIdentity)
            };

            int count = MysqlHelper.ExecuteNonQuery(sql, parameters);
            return count == 1;
        }

        private bool IsUserNameExists(string userAccount)
        {
            string sql = "SELECT COUNT(1) FROM user_info WHERE user_account = @UserAccount";
            var parameter = new MySqlParameter("@UserAccount", userAccount);

            var result = MysqlHelper.ExecuteScalar(sql, parameter);
            return Convert.ToInt32(result) > 0;
        }
        #endregion

        #region 修改按钮
        private void ExecuteUpdate(object obj)
        {
            if (!ValidateInput())
                return; // 验证失败，提前退出

            // 验证通过，执行修改逻辑
            try
            {
                // 是否成功
                if (UpdateUser())
                {
                    MsgBoxHelper.Success("用户更新成功");
                    _window.DialogResult = true; // 设置成功结果
                }
                else
                {
                    MsgBoxHelper.Error("用户更新失败");
                }
            }
            catch (MySqlException mysqlEx)
            {
                string friendlyMessage = mysqlEx.Number switch
                {
                    1042 => "无法连接数据库，请检查网络连接",
                    1045 => "数据库访问被拒绝",
                    1146 => "数据库表不存在",
                    1205 => "数据库操作超时，请重试", // 死锁
                    1213 => "事务死锁，请重试",      // 死锁
                    0 => "数据库连接失败，请检查网络",
                    _ => $"数据库操作失败，错误代码: {mysqlEx.Number}"
                };
                // 记录数据库异常的日志
                LogHelper.Error(this.GetType(), "[更新用户] | 数据库异常", mysqlEx, _currentUser.UserAccount);
                MsgBoxHelper.Error(friendlyMessage);
            }

            catch (Exception ex)
            {
                MsgBoxHelper.Error($"更新用户时出错：{ex.Message}");
                LogHelper.Error(this.GetType(), $"[更新用户] | 更新用户失败 用户账号:{NewUser.UserAccount}", ex, _currentUser.UserAccount);
            }
        }

        /// <summary>
        /// 执行修改 返回是否成功
        /// </summary>
        private bool UpdateUser()
        {
            string sql = @"UPDATE user_info 
                                SET user_account = @UserAccount,
                                user_password = @UserPassword,
                                user_name = @UserName,
                                user_identity = @UserIdentity
                                WHERE user_account = @OriginalUserAccount";

            var parameters = new[]
            {
                    new MySqlParameter("@UserAccount", NewUser.UserAccount),
                    new MySqlParameter("@UserPassword", NewUser.UserPassword),
                    new MySqlParameter("@UserName", NewUser.UserName),
                    new MySqlParameter("@UserIdentity", NewUser.UserIdentity),
                    new MySqlParameter("@OriginalUserAccount", _originalUser.UserAccount)
            };

            int count = MysqlHelper.ExecuteNonQuery(sql, parameters);
            return count == 1;
        }
        #endregion

        private void ExecuteClose(object obj)
        {
            _window.DialogResult = false;
        }

        private void InitThisWindowByActType(UserModel newUser, int actType)
        {
            if (newUser != null)
            {
                _isCheck1 = newUser.UserIdentity == 1;
                _isCheck2 = newUser.UserIdentity == 2;
            }

            if (actType == 2) // 修改
            {
                //IsDetailsEna = true;
                IsEditButtonVis = true;
                IsAddButtonVis = false;
            }
            else if (actType == 3) // 添加
            {
                //IsDetailsEna = true;
                IsEditButtonVis = false;
                IsAddButtonVis = true;
            }
            else
            {
                Debug.WriteLine("操作 [用户管理] 失败");
                MsgBoxHelper.Info("操作 [用户管理] 失败，未知操作类型");
                LogHelper.Info(this.GetType(), "[用户管理] | 操作 [用户管理] 失败，识别到未知操作类型", _currentUser.UserAccount);
                _window.DialogResult = false; // 设置取消结果
            }
        }

        /// <summary>
        /// 输入验证
        /// </summary>
        private bool ValidateInput()
        {
            // 检查空值
            if (string.IsNullOrEmpty(NewUser.UserAccount))
            {
                MsgBoxHelper.Warning("请输入用户账号");
                return false;
            }
            if (string.IsNullOrEmpty(NewUser.UserPassword))
            {
                MsgBoxHelper.Warning("请输入密码");
                return false;
            }
            if (string.IsNullOrEmpty(NewUser.UserName))
            {
                MsgBoxHelper.Warning("请输入姓名");
                return false;
            }
            if (NewUser.UserIdentity != 1 && NewUser.UserIdentity != 2)
            {
                MsgBoxHelper.Warning("请选择用户权限");
                return false;
            }

            return true;
        }
    }
}
